#pragma once


#include "Comm.hpp"


class HttpRequest
{
public:
    HttpRequest()
        : _version("HTTP/1.1")
    {}

    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        _headers.clear();
        _params.clear();

        std::smatch match;
        _matches.swap(match);
    }

    void SetHeader(const std::string& key, const std::string& val)
    {
        _headers.insert({ key, val });
    }

    bool HasHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it != _headers.end())
        {
            return true;
        }
        return false;
    }

    std::string GetHeader(const std::string& key) const 
    {
        auto it = _headers.find(key);
        if (it != _headers.end())
        {
            return it->second;
        }
        LOG(WARNING, "HttpRequest::GetHeader No such head: %s \n", key.c_str());
        return "";
    }

    void SetParmam(const std::string& key, const std::string& val)
    {
        _params.insert({ key, val });
    }

    bool HasParam(const std::string& key)
    {
        auto it = _params.find(key);
        if (it != _params.end())
        {
            return true;
        }
        return false;
    }

    std::string GetParam(const std::string& key)
    {
        auto it = _params.find(key);
        if (it != _params.end())
        {
            return it->second;
        }
        LOG(WARNING, "HttpRequest::GetParam There is no query string: %s \n", key.c_str());
        return "";
    }

    size_t GetContentSize()
    {
        bool ret = HasHeader("Content-Length");
        if (ret == false)
        {
            // LOG(WARNING, "HttpRequest::GetContentSize No header field Content-Length\n");
            return 0;
        }
        return std::stoi(GetHeader("Content-Length"));
    }

    bool HandleClose() const 
    {
        // LOG(INFO, "Connection: [%s]\n", GetHeader("Connection").c_str());
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive") {
            return false;
        }
        return true;
    }

public:
    std::string _method;
    std::string _path;
    std::string _version;
    std::string _body;
    
    std::smatch _matches;     // 资源路径的正则提取 

    std::unordered_map<std::string, std::string> _headers;
    std::unordered_map<std::string, std::string> _params;   // 查询字符串 
};


